//
//  SNHDImageViewController.m
//  DayDayHappy
//
//  Created by yutao on 14-2-23.
//  Copyright (c) 2014年 yutao. All rights reserved.
//

#import "SNHDImageViewController.h"
#import "SNCommentViewController.h"
#import "SNShareBoxView.h"

#define kShareClientServiceTypeWX  @"wx"

#define kUid        @"uid"
#define kAvatar     @"avatar"
#define kName       @"name"
#define kFrom       @"from"

@interface SNHDImageViewController ()<SNShareItemViewDelegate>

@property(nonatomic,strong)NSIndexPath *shareIndexPath;
@end

@implementation SNHDImageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [self.dbHelper createTableWithModelClass:[SNImageModel class]];
//        });
        
        [self.dbHelper createTableWithModelClass:[SNImageModel class]];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
     self.photoArray  = [[NSMutableArray alloc] initWithCapacity:1];
    
    BOOL hasUserInfoSina = [[ShareClientUserInfo defaultShareClientUser] hasUserInfoWithServiceType:kShareClientServiceTypeWeiBo];
    BOOL hasUserInfoQQ = [[ShareClientUserInfo defaultShareClientUser] hasUserInfoWithServiceType:kShareClientServiceTypeQQZone];
//    if (!hasUserInfoSina && !hasUserInfoQQ) {
//        [self initShareServiceNotifications];
//    }
//
//    [[ShareClientOAuthInfoQQ defaultShareClientOAuth] deleteOAuthInfo:[[ShareClientOAuthInfoQQ defaultShareClientOAuth] oAuthInfoWithServiceType:kShareClientServiceTypeQQZone] serviceType:kShareClientServiceTypeQQZone];
//
//        [[ShareClientOAuthInfoSina defaultShareClientOAuth] deleteOAuthInfo:[[ShareClientOAuthInfoSina defaultShareClientOAuth] oAuthInfoWithServiceType:kShareClientServiceTypeWeiBo] serviceType:kShareClientServiceTypeWeiBo];
//
//    [[ShareClientUserInfoQQ defaultShareClientUser] deleteUserInfo:[[ShareClientUserInfoQQ defaultShareClientUser] userInfoWithServiceType:kShareClientServiceTypeQQZone] serviceType:kShareClientServiceTypeQQZone];
////
//    [[ShareClientUserInfoQQ defaultShareClientUser] deleteUserInfo:[[ShareClientUserInfoQQ defaultShareClientUser] userInfoWithServiceType:kShareClientServiceTypeWeiBo] serviceType:kShareClientServiceTypeWeiBo];
//    [self initShareServiceNotifications];
    
    
}


- (void)initShareServiceNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userInfoDidLoad:) name:SNShareServiceDidLoadUserInfoNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareServiceDidLogin:) name:SNShareServiceDidLoginNotification object:nil];
    
}

- (void)shareServiceDidLogin:(NSNotification*)notification
{
//    ShareClientOAuthInfo *oauthInfo =  [ShareCenterServiceHandler shareServiceOauthInfoForNotification:notification];

}

- (void)shareMessageInfoWithType:(NSString *)serviceType
{
    ShareMessageInfo *shareMessage = [ShareMessageInfo message];
    SNImageModel *imageModel = self.contentDataArray[self.shareIndexPath.row];
    shareMessage.title = imageModel.content;
    shareMessage.imageData = UIImagePNGRepresentation([[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imageModel.image]);
    if ([serviceType isEqualToString:kShareClientServiceTypeWeiBo]) {
        [[ShareCenterEngine defaultEngine] shareMessage:shareMessage forServiceType:SNShareClientTypeSinaWeibo];
    }else if([serviceType isEqualToString:kShareClientServiceTypeQQZone]){
        [[ShareCenterEngine defaultEngine] shareMessage:shareMessage forServiceType:SNShareClientTypeQZone];
    }else{
        [[ShareCenterEngine defaultEngine] shareMessage:shareMessage forServiceType:SNShareClientTypeWeixinTimeline];
    }
    
}

- (void)userInfoDidLoad:(NSNotification*)notification
{
    ShareClientUserInfo *userInfo  = (ShareClientUserInfo *)[notification.userInfo objectForKey:SNShareServiceUserInfoKey]  ;
    //绑定用户用户信息
    AFHTTPClient * httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:kBaseUrl]];
    
    [httpClient setParameterEncoding:AFFormURLParameterEncoding];
    [httpClient postPath:kRegisterUser parameters:@{kUid:userInfo.uid,kAvatar:userInfo.iconURL,kName:userInfo.screenName,kFrom:userInfo.serviceType,} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"用户信息绑定成功");
        [self shareMessageInfoWithType:userInfo.serviceType];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"用户信息绑定失败");
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentif = @"cell";
    SNImageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentif];
    if (cell == nil) {
        cell = [[SNImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentif];
    }
    cell.delegate = self;
    [cell setUpImageCellWithObject:self.contentDataArray[indexPath.row] atIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self pushCommentViewControllerWithIndexPaht:indexPath];
}


- (void)pushCommentViewControllerWithIndexPaht:(NSIndexPath *)indexPath
{
    SNCommentViewController *commentViewController = [[SNCommentViewController alloc] init];
    commentViewController.hidesBottomBarWhenPushed = YES;
    SNImageModel *imageModel = self.contentDataArray[indexPath.row];
    commentViewController.model = imageModel;
    [self.navigationController pushViewController:commentViewController animated:YES];
}


- (void)imageCell:(SNImageCell *)imgCell didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*/Users/yutao/Desktop/myStudy/ShareCenter/ShareCenter/ShareCenter/SDKs/QQ
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = YES;
    browser.displaySelectionButtons = NO;
    browser.alwaysShowControls = NO;
    browser.wantsFullScreenLayout = YES;
    browser.zoomPhotosToFill = YES;
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    [browser setCurrentPhotoIndex:indexPath.row];
    
    // Modal
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:browser];
    navigationController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:navigationController animated:YES];
     */
    
}

- (void)commentButton:(UIButton *)commentBtn didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self pushCommentViewControllerWithIndexPaht:indexPath];
}


- (void)shareButton:(UIButton *)shareBtn didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.shareIndexPath = indexPath;
    NSDictionary * sinaDic = @{kImgKey: @"sns_icon_sina@2x",kTextKey:@"新浪微博"};
    NSDictionary * qqDic = @{kImgKey:@"sns_icon_qq@2x",kTextKey:@"QQ空间"};
    NSDictionary * wxDic = @{kImgKey:@"sns_icon_wx@2x",kTextKey:@"微信朋友圈"};
    NSMutableArray *snsShareItemArray  = [NSMutableArray arrayWithObjects:sinaDic,qqDic,wxDic, nil];
    
    SNShareBoxView * shareView = [[SNShareBoxView alloc] initWithFrame:[UIScreen mainScreen].bounds  shareArray:snsShareItemArray viewController:self type:SNShareBoxTypeShare];
    [self.tabBarController.view addSubview:shareView];
    [shareView show];
    
}

- (void)shareItemViewDidClick:(UIButton *)button
{
    if (button.tag == kButtonTagBase + 1) {
        
        /*
         request.userInfo = @{@"SSO_From": @"SendMessageToWeiboViewController",
         @"Other_Info_1": [NSNumber numberWithInt:123],
         @"Other_Info_2": @[@"obj1", @"obj2"],
         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
         
         */
        if ([self isHaveUserInfoWithType:kShareClientServiceTypeWeiBo]) {
            [self shareMessageInfoWithType:kShareClientServiceTypeWeiBo];
        }else{
            [[ShareCenterEngine defaultEngine] loginForServiceType:SNShareClientTypeSinaWeibo];
        }
        
    }else if(button.tag == kButtonTagBase + 2){
        
        if ([self isHaveUserInfoWithType:kShareClientServiceTypeQQZone]) {
            [self shareMessageInfoWithType:kShareClientServiceTypeQQZone];
        }else{
            [[ShareCenterEngine defaultEngine] loginForServiceType:SNShareClientTypeQZone];
        }
        
    }else{
        [self shareMessageInfoWithType:kShareClientServiceTypeWX];
    }
}

- (BOOL)isHaveUserInfoWithType:(NSString *)type
{
    if ([type isEqualToString:kShareClientServiceTypeWeiBo] || [type isEqualToString:kShareClientServiceTypeQQZone]) {
        
        return [[ShareClientUserInfoQQ defaultShareClientUser] hasUserInfoWithServiceType:kShareClientServiceTypeQQZone]
               || [[ShareClientUserInfoSina defaultShareClientUser] hasUserInfoWithServiceType:kShareClientServiceTypeWeiBo];
        
    }else{
        return NO;
    }
    
}

- (UIImage *)defaultImage
{
    return [UIImage imageNamed:@"icon.png"];
}


- (UIImage *)imageFromCacheWithUrl:(NSString*)imgUrl
{
    UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imgUrl];
    
    return image ? image : [self defaultImage];
}

#pragma mark - MWPhotoBrowserDelegate


-(Class)currModel
{
    return [SNImageModel class];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
